package soap;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.time.Clock;
import java.util.concurrent.CountDownLatch;

import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapHandler;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.config.NetworkConfig;
import org.eclipse.californium.elements.tcp.TcpClientConnector;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;

import dtls.DtlsServer;

public class DtlsClient {

	public static void main(String[] args) throws Exception {
		
		InputStream in = DtlsServer.class.getResourceAsStream(DtlsServer.KEY_STORE_LOCATION);
		KeyStore keyStore = KeyStore.getInstance("jks");
		keyStore.load(in, DtlsServer.KEY_STORE_PASSWORD.toCharArray());
		in.close();
		
		KeyStore trustStore = KeyStore.getInstance("jks");
		in = DtlsServer.class.getResourceAsStream(DtlsServer.TRUST_STORE_LOCATION);
		trustStore.load(in, DtlsServer.TRUST_STORE_PASSWORD.toCharArray());
		in.close();
		
		Certificate[] cert = new Certificate[1];
		cert[0] = trustStore.getCertificate("root");
		
		DtlsConnectorConfig.Builder builder = 
				new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
		builder.setIdentity((PrivateKey)keyStore.getKey("client", DtlsServer.KEY_STORE_PASSWORD.toCharArray()), 
				keyStore.getCertificateChain("client"), true);
		builder.setTrustStore(cert);
		final DTLSConnector connector = new DTLSConnector(builder.build());
		
		int count = 1;
		CountDownLatch countDown = new CountDownLatch(count);
		long start = Clock.systemUTC().millis();
		CoapClient client = new CoapClient("coaps://127.0.0.1:5685/sync?appKey=zq6NDc3sb6QmoQF1&appSecret=PosmJNUoMLD777Nf7tlu");
		client.setEndpoint(new CoapEndpoint(connector, NetworkConfig.getStandard()));
//		client.useCONs();
		for(int i = 0; i < count; i++){
			
			client.post(new CoapHandler() {
				
				@Override
				public void onLoad(CoapResponse response) {
					System.out.println(Utils.prettyPrint(response));
//					tcpConnector.stop();  //tcp是长连接，所以要手动关闭连接
//					tcpConnector.destroy();
					client.shutdown();
					countDown.countDown();
				}
				
				@Override
				public void onError() {
					// TODO Auto-generated method stub
					
				}
			}, "111", MediaTypeRegistry.TEXT_PLAIN);
		}
		countDown.await();
		long end = Clock.systemUTC().millis();
//		System.out.println(end - start);
	}
}
